from rest_framework import serializers
from .models import UserInformation
import re
from django.contrib.auth.models import User


class LoginSerializer(serializers.Serializer):  # 用于登录的表单合法性验证，防止绕过前端验证
    username = serializers.CharField()
    password = serializers.CharField()
    remember = serializers.BooleanField()

    def validate_username(self, username):
        if len(username) < 5 or len(username) > 18:
            raise serializers.ValidationError("用户名长度不正确")
        elif re.match('^[a-zA-Z0-9_]{5,18}$', username) is None:
            raise serializers.ValidationError("用户名不符合规定")
        else:
            return username

    def validate_password(self, password):
        if len(password) != 32:
            raise serializers.ValidationError("密码长度不正确")
        else:
            return password


class RegisterSerializer(serializers.Serializer):  # 用于注册的表单合法性验证，防止绕过前端验证
    username = serializers.CharField()
    password = serializers.CharField()
    email = serializers.CharField()
    nickname = serializers.CharField()

    def validate_username(self, username):
        if len(username) < 5 or len(username) > 18:
            raise serializers.ValidationError("用户名长度不正确")
        elif re.match('^[a-zA-Z0-9_]{5,18}$', username) is None:
            raise serializers.ValidationError("用户名不符合规定")
        else:
            return username

    def validate_password(self, password):
        if len(password) != 32:
            raise serializers.ValidationError("密码长度不正确")
        else:
            return password

    def validate_email(self, email):
        if re.match('^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email) is None:
            raise serializers.ValidationError("邮箱不符合规定")
        else:
            return email

    def validate_nickname(self, nickname):
        if re.match('^[a-zA-Z0-9\u4e00-\u9fa5_丶]{2,18}$', nickname) is None:
            raise serializers.ValidationError("用户名不符合规定")
        else:
            return nickname
